﻿package CustomCMS 
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.*;
	/**
	* ...
	* @author DefaultUser (Tools -> Custom Arguments...)
	*/
	public class WebRequest 
	{
		
		public function WebRequest() 
		{
			
		}
				
		public static function Get(url:String, callback:Function, params:Array, errorCallback:Function=null) : void
		{			
			url += "?";
			
			for( var count:int=0;count < params.length; count++)
				url += params[count].name + "=" + params[count].val + "&";
				
			url += "random=" + Math.random() + "&version=" + Util.Version;
			//url = url.substr(0,url.length-1);
			
			try
			{
				var request:URLRequest = new URLRequest(url);
				var loader:URLLoader = new URLLoader();
			}
			catch(e:Error)
			{
				if (errorCallback != null) errorCallback(new ErrorEvent(e.name, false, false, e.message));
			}

			loader.dataFormat = URLLoaderDataFormat.TEXT;			
			loader.addEventListener(Event.COMPLETE, callback);
			if (errorCallback != null) 
			{
				loader.addEventListener(flash.events.IOErrorEvent.IO_ERROR, errorCallback);
				loader.addEventListener(flash.events.SecurityErrorEvent.SECURITY_ERROR, errorCallback);
			}
			loader.load(request);
		}

		public static function Post(url:String, callback:Function, variables:URLVariables, errorCallback:Function=null) : void
		{
			var request:URLRequest = new URLRequest(url);
			var loader:URLLoader = new URLLoader();
			request.method = URLRequestMethod.POST;
			 			
			variables.version = Util.Version;
			
			// assign the data to be sent by POST
			request.data = variables;
			
			loader.dataFormat = URLLoaderDataFormat.TEXT;			
			loader.addEventListener(Event.COMPLETE, callback);
			if (errorCallback != null) 
			{
				loader.addEventListener(flash.events.IOErrorEvent.IO_ERROR, errorCallback);
				loader.addEventListener(flash.events.SecurityErrorEvent.SECURITY_ERROR, errorCallback);
			}
			loader.load(request);
		}	
	}
}